<?php
class ModelCatalogNewsFeed extends Model {		
	
	/**
     * Retrieve a single news item.
     */	 
	public function getNewsById($news_id, $start = 0, $limit = 1) {
		$query = $this->db->query("SELECT news_item FROM " . DB_PREFIX . "news_item ni LEFT JOIN " . DB_PREFIX . "news i ON (ni.news_id = i.news_id) WHERE ni.news_id = '" . (int)$news_id . "' AND i.is_published = '1' AND ni.language_id = '" . (int)$this->config->get('config_language_id') . "' LIMIT " . (int)$start . "," . (int)$limit);
		
		return $query->rows;
	}	
	
	/**
	 * Function will try to return a random news item from the table.
	 */
	public function getRandomNewsItem() {

		// Fetch all published news ids
		$all_published_news = $this->db->query("SELECT news_id FROM " . DB_PREFIX . "news WHERE is_published = 1");
		
		$news_array = $all_published_news->rows;
		
		if (!empty($news_array)) {
		
			// Select a random array position from the subset
			$random_number = array_rand($news_array, 1);
			
			// Get a random row id from the subset
			$random_id = $news_array[$random_number]['news_id'];
			
			// Now retrieve the news_id
			$random_sql = "SELECT news_item FROM " . DB_PREFIX . "news_item WHERE news_id = '" . $random_id . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "' LIMIT 1";

			$random_news_item = $this->db->query($random_sql);
		}
		
		$final_result = '';
		
		if (isset($random_news_item->row['news_item'])) {
			$final_result = $random_news_item->row['news_item'];
		} 
		
		return $final_result;
	}
}
?>